package com.zh.zcy.untils;

import com.zh.zcy.entity.User;

/**
 * 用户信息ThreadLocal存储
 */
public class UserContextUtil {
    //使用ThreadLocal 并设置初始值
    private static final ThreadLocal<User> userContext = ThreadLocal.withInitial(User::new);

    //获取当前线程的用户信息
    public static User getUser(){
        return userContext.get();
    }

    //存储用户信息
    public static void setUser(User user){
        if(user == null){
            throw new IllegalArgumentException("User cannot be null");
        }
        userContext.set(user);
    }

    //清除用户信息，必须清除，否则会有内存泄漏风险
    public static void clear(){
        userContext.remove();
    }
}
